'''
优点：
    1）远程代理：可以隐藏对象位于远程地址空间的事实
    2）虚代理：可以进行优化，例如根据要求创建对象
    3）保护代理：允许在访问一个对象时有一些附加的内务处理。
'''
from abc import ABCMeta, abstractmethod


class Subject(metaclass=ABCMeta):
    @abstractmethod
    def get_content(self):
        pass

    @abstractmethod
    def set_content(self,content):
        pass


class RealSubject(Subject):
    def __init__(self,filename):
        self.filename = filename
        with open(filename,'rb') as f:
            self.content = f.read()
        
    def get_content(self):
        return self.content

    def set_content(self, content):
        with open(self.filename,'wb') as f:
            f.write(content)

class VirtuallProxy(Subject):
    def __init__(self,filename) :
        self.filename = filename
        self.subj = None

    def get_content(self):
        if not self.subj:
           self.subj = RealSubject(self.filename)
        return self.subj.get_content()

    def set_content(self, content):
        if not self.subj:
           self.subj = RealSubject(self.filename)
        self.subj.set_content(content)
    

class ProtectedProxy(Subject):
    def __init__(self,filename) -> None:
        self.subj = RealSubject(filename)

    def get_content(self):
        return self.subj.get_content()
    def set_content(self,content):
        raise PermissionError("无写入权限")

if __name__ == "__main__":
    VirtuallProxy("text.txt")
